import 'dart:math';

import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/ui/utils/progress_view.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';

import 'ShowPic.dart';
import 'model/share_entity.dart';
import 'model/ts_pic_entity.dart';
import 'model/tsactivity_entity.dart';
import 'package:webview_flutter/webview_flutter.dart';
class SharePageForTs extends StatefulWidget {
  @override
  _SharePageForTsState createState() => _SharePageForTsState();
}

class _SharePageForTsState extends State<SharePageForTs> {
  MyPageState ps = MyPageState.LOADING;
  TsPicEntity tsPicEntity = null;
  ShareEntity entity = null;
  TsactivityEntity _tsactivityEntity = null;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.c243,
      appBar: UiUtils.appBar(context, "推手权益"),
      body: getBody(),
    );
  }

  getBody() {
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    if (ps == MyPageState.HAVE_DATA) {
      List<Widget> list = [];
      list.add(getRow1());
      _tsactivityEntity.data.forEach((item) {
        list.add(getActivityItem(item));
      });

      return EasyRefresh(
        child: ListView(
          children: list,
        ),
      );
    }
  }

  Widget getRow1() {
    return Container(
      child: Stack(
        fit: StackFit.loose,
        overflow: Overflow.clip,
        children: <Widget>[
          Container(
            height: ScreenUtil().setWidth(820),
            child: Column(
              children: <Widget>[
                Container(
                  height: ScreenUtil().setWidth(480),
                  child: CachedNetworkImage(
                    width: ScreenUtil().setWidth(750),
                    fit: BoxFit.cover,
                    imageUrl: tsPicEntity.data,
                    placeholder: (context, url) => new ProgressView(),
                    errorWidget: (context, url, error) => new Icon(
                      Icons.error,
                      color: Colors.redAccent,
                    ),
                  ),
                )
              ],
            ),
          ),
          Positioned(
            bottom: 0,
            right: ScreenUtil().setWidth(20),
            left: ScreenUtil().setWidth(20),
            child: Container(
              height: ScreenUtil().setWidth(540),
              decoration: BoxDecoration(
                border: new Border.all(color: Colours.bgec, width: 0.5),
                borderRadius: BorderRadius.circular(10),
                color: Colors.white,
              ),
              child: Column(
                children: <Widget>[
                  getItemLink("专属邀请注册:", entity.data.code),
                  getItemLink("邀请快速做单:", entity.data.kslink),
                  getRow2(entity.data.qrcode),
                  getMiddle()
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  void getData() {
    DioManager.getInstance().post(Api.USER_ACTIVITYPIC, null, (json) {
      tsPicEntity = TsPicEntity.fromJson(json);
      if (null == tsPicEntity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }

      if (tsPicEntity.code != 200) {
        ToastUtil.showShortErrToast(tsPicEntity.message);
        NavigatorUtils.goBack(context);
        return;
      }
      getInvite();
    }, (err) {
      NavigatorUtils.goBack(context);
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
    });
  }

  Widget getItemLink(String s, String code) {
    return Container(
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(20),
          right: ScreenUtil().setWidth(30),
          top: ScreenUtil().setWidth(30)),
      child: Row(
        children: <Widget>[
          Container(
            child: Text(
              s,
              style: TextStyles.custom(
                  30, Colours.appC16, Font.PingFangMedium),
            ),
          ),
          Container(
            child: Text(
              getLink(code),
              style: TextStyles.custom(
                  30, Colours.appC16, Font.PingFangMedium),
            ),
          ),
          InkWell(
            onTap: () {
              ClipboardData data = new ClipboardData(text: code);
              Clipboard.setData(data);
              ToastUtil.showShortToast("已复制");
            },
            child: Container(
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
              child: Icon(
                Icons.content_copy,
                size: 18,
                color: Colours.appC16,
              ),
            ),
          )
        ],
      ),
    );
  }

  String getLink(String code) {
    StringBuffer sb = new StringBuffer();
    sb.write(code.substring(0, 9));
    sb.write("******");
    sb.write(code.substring(code.length - 6, code.length));
    return sb.toString();
  }

  Widget getRow2(String qrcode) {
    return GestureDetector(
      onTap: () {
        showDialog(
            context: context,
            builder: (BuildContext context) {
              return ShowPicPage(qrcode);
            });
      },
      child: Container(
        color: Colors.white,
        child: Container(
          margin: EdgeInsets.fromLTRB(
              ScreenUtil().setWidth(120),
              ScreenUtil().setWidth(30),
              ScreenUtil().setWidth(120),
              ScreenUtil().setWidth(30)),
          height: ScreenUtil().setWidth(80),
          decoration: BoxDecoration(
            color: Colours.appC16, // 底色
            gradient: LinearGradient(colors: <Color>[
              Color(0xFFffc75d),
              Color(0xFFff8d16),
            ], begin: Alignment.topCenter, end: Alignment.bottomCenter),
            borderRadius: new BorderRadius.circular(20), // 圆角度 steelseries
            //  borderRadius: new BorderRadius.vertical(top: Radius.elliptical(20, 50)), // 也可控件一边圆角大小
          ),
          alignment: Alignment.center,
          child: Text(
            "查看我的推广海报",
            style: TextStyles.custom(
                32, Colours.white, Font.PingFangMedium),
          ),
        ),
      ),
    );
  }

  Widget getMiddle() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(
          left: ScreenUtil().setWidth(30),
          right: ScreenUtil().setWidth(30),
          top: ScreenUtil().setWidth(20),
          bottom: ScreenUtil().setWidth(20)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            child: Row(
              children: <Widget>[
                Container(
                  child: Image.asset(
                    Utils.getImgPath("icon_share"),
                    width: 45,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        child: Text(
                          "邀请奖励",
                          style: TextStyles.custom(
                              36, Colours.appC1, Font.PingFangBlod),
                        ),
                      ),
                      Container(
                        child: Text(
                          "活动时间： 2019-08-20 至 2029-08-20",
                          style: TextStyles.custom(
                              28, Colours.appC2, Font.PingFangRegular),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(16)),
            child: Text(
              "直接邀请奖励刷手佣金的8%",
              style: TextStyles.custom(
                  28, Colours.appC2, Font.PingFangRegular),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(10)),
            child: Text(
              "间接邀请奖励刷手佣金的2%",
              style: TextStyles.custom(
                  28, Colours.appC2, Font.PingFangRegular),
            ),
          )
        ],
      ),
    );
  }

  Widget getBottom() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
      padding: EdgeInsets.only(top: ScreenUtil().setWidth(30)),
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            width: ScreenUtil().setWidth(690),
            height: ScreenUtil().setWidth(120),
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage(Utils.getImgPath("bg_invite")),
                  fit: BoxFit.fitWidth),
            ),
            child: Text(
              "我的邀请记录",
              style: TextStyles.custom(
                  30, Colours.appC2, Font.PingFangMedium),
            ),
          ),
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                getItemBottom(entity.data.num, "直接邀请（人）"),
                getItemBottom(entity.data.indirect, "间接邀请（人）"),
                getItemBottom(entity.data.money, "我的收入（金）", isMoney: true),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.all(ScreenUtil().setWidth(30)),
            child: UiUtils.divider(height: 2),
          ),
          Container(
              margin: EdgeInsets.only(bottom: ScreenUtil().setWidth(30)),
              child: Text(
                "本次活动解释权归巨沃所有",
                style: TextStyles.custom(
                    26, Colours.appC3, Font.PingFangRegular),
              ))
        ],
      ),
    );
  }

  getItemBottom(String num, String text, {bool isMoney = false}) {
    return GestureDetector(
      onTap: () {
        if (isMoney) {
          ///跳转到我的收入页面
          NavigatorUtils.push(context, Routes.myIncome);
        }
      },
      child: Container(
        margin: EdgeInsets.only(
            top: ScreenUtil().setWidth(20), bottom: ScreenUtil().setWidth(20)),
        child: Column(
          children: <Widget>[
            Text(
              num,
              style: TextStyles.custom(
                  36,
                  isMoney ? Colours.appC16 : Colours.appC1,
                  Font.PingFangMedium),
            ),
            Text(
              text,
              style: TextStyles.custom(
                  26, Colours.appC2, Font.PingFangRegular),
            )
          ],
        ),
      ),
    );
  }

  void getInvite() {
    DioManager.getInstance().post(Api.USER_GETINVITE, null, (json) {
      entity = ShareEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }

      if (entity.code != 200) {
        ToastUtil.showShortErrToast(entity.message);
        NavigatorUtils.goBack(context);
        return;
      }
      getTsActivity();
    }, (err) {
      NavigatorUtils.goBack(context);
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
    });
  }

  void getTsActivity() {
    DioManager.getInstance().post(Api.USER_TSACTIVITY, null, (json) {
      _tsactivityEntity = TsactivityEntity.fromJson(json);
      if (null == _tsactivityEntity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }

      if (_tsactivityEntity.code != 200) {
        ToastUtil.showShortErrToast(_tsactivityEntity.message);
        NavigatorUtils.goBack(context);
        return;
      }

      ps = MyPageState.HAVE_DATA;
      setState(() {});
    }, (err) {
      NavigatorUtils.goBack(context);
      ToastUtil.showShortErrToast(Api.ERR_NOTHING);
    });
  }

  Widget getActivityItem(TsactivityData item) {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(20), ScreenUtil().setWidth(20), 0),
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(20),
          ScreenUtil().setWidth(20)),
      decoration: BoxDecoration(
        border: new Border.all(color: Colours.bgec, width: 0.5),
        borderRadius: BorderRadius.circular(10),
        color: Colors.white,
      ),
      child: Column(
        children: <Widget>[
          Container(
            child: Row(
              children: <Widget>[
                Container(
                  child: UiUtils.cachedNetworkImage(90, 90, item.pic),
                ),
                Container(
                  margin: EdgeInsets.only(left: ScreenUtil().setWidth(20)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        child: Text(
                          "${item.actiName}",
                          style: TextStyles.custom(
                              36, Colours.appC1, Font.PingFangBlod),
                        ),
                      ),
                      Container(
                        child: Text(
                          "活动时间：${item.startTime.substring(5, item.startTime.length - 3)}至 ${item.endTime.substring(5, item.endTime.length - 3)}",
                          style: TextStyles.custom(
                              28, Colours.appC2, Font.PingFangRegular),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
          Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
            child: Text(
              "活动规则:",
              style: TextStyles.custom(
                  26, Colours.appC2, Font.PingFangRegular),
            ),
          ),Container(
            child: Html(
              data: item.explain,
              blockSpacing: 0,
            ),
          ),
        /*  Container(
            height: ScreenUtil().setWidth(450),
            child:  WebView(
              initialUrl: "https://www.baidu.com/",
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (WebViewController webViewController) {
                ///_controller.complete(webViewController);
              },
              // TODO(iskakaushik): Remove this when collection literals makes it to stable.
              // ignore: prefer_collection_literals
             javascriptChannels: <JavascriptChannel>[
                _toasterJavascriptChannel(context),
              ].toSet(),
              navigationDelegate: (NavigationRequest request) {
                if (request.url.startsWith('https://www.youtube.com/')) {
                  print('blocking navigation to $request}');
                  return NavigationDecision.prevent;
                }
                print('allowing navigation to $request');
                return NavigationDecision.navigate;
              },
              onPageFinished: (String url) {
                print('Page finished loading: $url');
              },
            ),
          )*/
        ],
      ),
    );
  }

  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }
}
